package com.example.personalizededucationsystem.service;

import com.example.personalizededucationsystem.dto.request.SubmitAnswerRequest;
import com.example.personalizededucationsystem.dto.response.AnswerFeedbackResponse;
import com.example.personalizededucationsystem.model.AnswerRecord;
import com.example.personalizededucationsystem.model.ErrorNotebook;
import com.example.personalizededucationsystem.model.Question;
import com.example.personalizededucationsystem.model.User;
import com.example.personalizededucationsystem.repository.AnswerRecordRepository;
import com.example.personalizededucationsystem.repository.ErrorNotebookRepository;
import com.example.personalizededucationsystem.repository.QuestionRepository;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PracticeService {

    private final QuestionRepository questionRepository;
    private final AnswerRecordRepository answerRecordRepository;
    private final ErrorNotebookRepository errorNotebookRepository;

    @Autowired
    public PracticeService(QuestionRepository questionRepository, AnswerRecordRepository answerRecordRepository, ErrorNotebookRepository errorNotebookRepository) {
        this.questionRepository = questionRepository;
        this.answerRecordRepository = answerRecordRepository;
        this.errorNotebookRepository = errorNotebookRepository;
    }

    @Transactional
    public AnswerFeedbackResponse checkAnswer(Long questionId, SubmitAnswerRequest request, User student) {
        Question question = questionRepository.findById(questionId)
                .orElseThrow(() -> new EntityNotFoundException("题目未找到，ID: " + questionId));

        Set<String> expected = normalizeAnswer(question.getAnswer());
        Set<String> user = normalizeAnswer(request.getUserAnswer());
        boolean isCorrect = expected.equals(user);

        AnswerRecord record = new AnswerRecord();
        record.setStudent(student);
        record.setQuestion(question);
        record.setUserAnswer(request.getUserAnswer());
        record.setCorrect(isCorrect);
        answerRecordRepository.save(record);

        if (!isCorrect) {
            handleErrorNotebook(student, question);
        }

        AnswerFeedbackResponse feedback = new AnswerFeedbackResponse();
        feedback.setCorrect(isCorrect);
        feedback.setCorrectAnswer(question.getAnswer());
        feedback.setAnalysis(question.getAnalysis());

        return feedback;
    }

    private void handleErrorNotebook(User student, Question question) {
        ErrorNotebook errorRecord = errorNotebookRepository.findByStudentAndQuestion(student, question)
                .orElse(new ErrorNotebook());

        if (errorRecord.getErrorId() == null) {
            errorRecord.setStudent(student);
            errorRecord.setQuestion(question);
        } else {
            errorRecord.setErrorCount(errorRecord.getErrorCount() + 1);
            errorRecord.setLastErrorAt(Instant.now());
        }
        errorNotebookRepository.save(errorRecord);
    }

    public List<ErrorNotebook> getStudentErrorNotebook(User student, String subject) {
        return errorNotebookRepository.findByStudentAndSubjectName(student, subject);
    }

    private Set<String> normalizeAnswer(String answer) {
        if (answer == null || answer.isBlank()) return Set.of();
        return answer.chars()
                .filter(c -> c >= 'A' && c <= 'Z')
                .mapToObj(c -> String.valueOf((char) c))
                .collect(Collectors.toSet());
    }

}